package gupao.concurrency.demo.risk.controller;

import gupao.concurrency.demo.risk.calc.processor.CalcThreadPoolService;
import gupao.concurrency.demo.risk.exct.ExctService;
import gupao.concurrency.demo.risk.model.RiskJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PreDestroy;
import java.util.Random;
import java.util.concurrent.*;

@Slf4j
@RestController
public class RiskJobController {

    @Autowired
    private ExctService exctService;

    private final ExecutorService executor = new ThreadPoolExecutor(4, 8,
                1L,TimeUnit.MINUTES,
                new ArrayBlockingQueue<Runnable>(1000000),
                new CalcThreadPoolService.SimpleThreadFactory("risk-job-thread-"));

    @RequestMapping("/newjob")
    public String createRiskJob(){
        RiskJob job = createOrQueryJob();
        try{
            executor.execute(() -> exctService.exct(job));
            log.info("create job {} successful, will calc automatically", job.getId());
            return "succ";
        }catch (RejectedExecutionException e){
            log.error("reject job: {}", job.getId(), e);
            return "fail";
        }
    }

    @PreDestroy
    public void shutdown(){
        executor.shutdown();
    }

    private RiskJob createOrQueryJob(){
        return new RiskJob(new Random().nextLong());
    }
}
